package com.three.digit.tools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SynThread extends Thread {

	private static final Pattern pattern = Pattern
			.compile("<li class=\"blue\">(\\d){1}</li>\\s*<li class=\"blue\">(\\d){1}</li>\\s*<li class=\"blue\">(\\d){1}</li>");

	private static final String urlString = "http://kaijiang.zhcw.com/zhcw/inc/3d/3d_index.jsp";

	private static Integer count = 0;

	private boolean finish = false;

	private String id;

	public SynThread(String id) {
		this.id = id;
	}

	@Override
	public void run() {
		try {
			System.out.println(id + "  " + parseString(getStr(id)));
		} catch (Exception e) {
		}
		synchronized (count) {
			count++;
		}
		finish = true;
	}

	private String parseString(String str) {
		StringBuffer sb = new StringBuffer();
		Matcher matcher = pattern.matcher(str);

		while (matcher.find() && matcher.groupCount() > 0) {
			for (int i = 1, ii = matcher.groupCount(); i <= ii; i++) {
				sb.append(matcher.group(i));
			}
		}
		return sb.toString();
	}

	private String getStr(String id) {

		String rtn = "";
		HttpURLConnection urlconn = null;
		InputStream is = null;

		try {

			URL url = new URL(urlString);

			urlconn = (HttpURLConnection) url.openConnection();

			urlconn.setDoOutput(true);
			urlconn.setRequestMethod("POST");

			StringBuffer param = new StringBuffer();
			param.append("issue=" + id);

			OutputStream os = urlconn.getOutputStream();
			os.write(param.toString().getBytes());
			os.close();

			is = urlconn.getInputStream();

			rtn = readFromStream(is);

		} catch (Exception e) {
			try {
				rtn = urlconn.getResponseMessage();
			} catch (Exception e2) {
				// TODO: handle exception
			}
			// System.out.println("Internal Server Error".equals(el.getMessage()));
			throw new RuntimeException(rtn);
		} finally {
			urlconn.disconnect();
		}

		return rtn;
	}

	private String readFromStream(InputStream inputStream) {

		StringBuffer sb = new StringBuffer();

		BufferedReader br = null;

		try {
			br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

			String str;
			while ((str = br.readLine()) != null) {
				sb.append(str);
			}

		} catch (Exception e) {
			e.printStackTrace();

		} finally {
			try {
				inputStream.close();
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	public static int getCount() {
		return count;
	}

	public boolean isFinish() {
		return finish;
	}
}
